//
//  UDLoginViewController.swift
//  Chatter
//
//  Created by David on 16/7/13.
//  Copyright © 2016年 David. All rights reserved.
//  登陆

import UIKit

class UDLoginViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UDLoginRegDelegate {

    let DOCUMENT_PATH = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
    
    private var tableView:UITableView!
    var navigationBar:UINavigationBar!
    
    private var emailTextField:UDTextField!
    private var passwordTextField:UDTextField!
    private var verifyTextField:UDTextField!
    //private var forgetPswBtn:UIButton!
    private var verifyImg:UIButton!
    private var loginBtn:UIButton!
    private var msg:UILabel!
    
    private var spinnerBG:UIView!
    private var verifyNeed = false
    private var requireVerify:Bool{
        get{
            return verifyNeed
        }
        set(val){
            verifyNeed = val
            
            if val{
                self.passwordTextField.returnKeyType = .Next
                self.verifyTextField.alpha = 1
                //self.forgetPswBtn.frame.origin.y = self.verifyImg.frame.origin.y
                self.verifyImg.alpha = 1
                refreshVerifyImg()
                
            }
        }
    }
    @objc private func refreshVerifyImg(){
        NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.GET_VERIFY)")!), queue: NSOperationQueue(), completionHandler: { (resp:NSURLResponse?, returnData:NSData?, err:NSError?) in
            if err == nil{
                if let data = returnData{
                    
                    // MARK: print cookie
                    /*
                    for cookie in NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies!{
                        print(cookie)
                    }
                    */
                    
                    dispatch_async(dispatch_get_main_queue(), {
                        self.verifyImg.setImage(UIImage(data: data), forState: .Normal)
                    })
                }
            }
        })
    }
    
    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return .LightContent
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 使用check&jump
//        if NSUserDefaults.standardUserDefaults().objectForKey("user") != nil{
            // 跳转至其他页面
//            presentViewController(mainViewController, animated: false, completion: { 
//                
//            })
//            return
//        }
        //view.backgroundColor = UIColor.whiteColor()
        
        
        
        tableView = UITableView(frame: CGRect(x: 0, y: 64, width: view.bounds.width, height: view.bounds.height - 64), style: .Grouped)
        tableView.keyboardDismissMode = .OnDrag
        tableView.allowsSelection = false
        self.view.addSubview(tableView)
        
        msg = UILabel(frame: CGRect(x: 0, y: 40, width: self.view.frame.width, height: 24))
        msg.textAlignment = .Center
        msg.font = UIFont.systemFontOfSize(12)
        
        msg.textColor = UIColor.brownColor()
        msg.backgroundColor = UIColor.orangeColor()
        msg.alpha = 0
        msg.center.y = 52
        view.addSubview(msg)
        
        navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 64))
        view.addSubview(navigationBar)
        navigationBar.barStyle = .Black
        navigationBar.tintColor = UIColor.whiteColor()
        navigationBar.barTintColor = Fatcat.THEME_COLOR
        
        let navItem = UINavigationItem(title: "登陆")
        navigationBar.pushNavigationItem(navItem, animated: true)
        // MARK:注册按钮
        navItem.rightBarButtonItem = UIBarButtonItem(title: "注册", style: .Plain, target: self, action: #selector(UDLoginViewController.gotoReg))
        navItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Stop, target: self, action: #selector(UDLoginViewController.dismiss))
        
        emailTextField = UDTextField(frame: CGRect(x: 16, y: 8, width: self.view.frame.width - 32, height: 32))
        emailTextField.boderWidth = 0
        emailTextField.addTarget(self, action: #selector(UDLoginViewController.nextInput(_:)), forControlEvents: .EditingDidEndOnExit)
        
        passwordTextField = UDTextField(frame: CGRect(x: 16, y: 8, width: self.view.frame.width - 32, height: 32))
        passwordTextField.boderWidth = 0
        passwordTextField.textFieldType = .Password
        passwordTextField.addTarget(self, action: #selector(UDLoginViewController.nextInput(_:)), forControlEvents: .EditingDidEndOnExit)
        
        verifyTextField = UDTextField(frame: CGRect(x: 16, y: 8, width: self.view.bounds.width - 8 - 83.2 - 32, height: 32))
        verifyTextField.boderWidth = 0
        verifyTextField.textFieldType = .Verify
        verifyTextField.addTarget(self, action: #selector(UDLoginViewController.nextInput(_:)), forControlEvents: .EditingDidEndOnExit)
        
        // MARK:DEL: forget password
        /*
        forgetPswBtn = UIButton(type: .System)
        forgetPswBtn.frame = CGRect(x: 8, y: 24 + emailTextField.frame.height + 8 + passwordTextField.frame.height + 8 + verifyTextField.frame.height + 8, width: 75, height: 32)
        forgetPswBtn.setTitle("忘记密码", forState: .Normal)
        forgetPswBtn.titleLabel?.textAlignment = .Left
//        self.scrollView.addSubview(self.forgetPswBtn)
        */
        
        verifyImg = UIButton(frame: CGRect(x: self.view.bounds.width - 83.2 - 16, y: 8, width: 83.2, height: 32))
        verifyImg.backgroundColor = UIColor.grayColor()
        verifyImg.contentMode = .ScaleToFill
        verifyImg.addTarget(self, action: #selector(UDLoginViewController.refreshVerifyImg), forControlEvents: .TouchUpInside)
        
        
        
        loginBtn = UIButton(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 48))
        loginBtn.setTitle("登陆", forState: .Normal)
        loginBtn.backgroundColor = Fatcat.THEME_COLOR
        loginBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        loginBtn.addTarget(self, action: #selector(UDLoginViewController.login), forControlEvents: .TouchUpInside)
        loginBtn.adjustsImageWhenDisabled = true
        
        //checkNeedVerify()
        
        spinnerBG = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        spinnerBG.center = view.center
        spinnerBG.backgroundColor = UIColor(white: 0, alpha: 0.75)
        spinnerBG.layer.cornerRadius = 5
        view.addSubview(spinnerBG)
        let spinner = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        spinner.center = CGPoint(x: 25, y: 25)
        spinner.activityIndicatorViewStyle = .White
        spinner.startAnimating()
        spinnerBG.addSubview(spinner)
        
        
        self.spinnerBG.alpha = 0
        
        requireVerify = true
        
        tableView.delegate = self
        tableView.dataSource = self
        
        self.emailTextField.becomeFirstResponder()
        
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            return 3
        }
        return 1
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 48
    }
    /*
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0{
            return 32
        }
        if section == 1{
            return 1
        }
        return 0
    }
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0{
            return msg
        }
        return nil
    }
    */
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .Default, reuseIdentifier: "row")
        if indexPath.section == 0{
            switch indexPath.row {
            case 0:
                cell.addSubview(emailTextField)
                break
            case 1:
                cell.addSubview(passwordTextField)
                break
            case 2:
                cell.addSubview(verifyTextField)
                cell.addSubview(verifyImg)
                break
            default:
                break
            }
        }else if indexPath.section == 1 && indexPath.row == 0 {
            cell.addSubview(loginBtn)
        }
        return cell
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @objc private func nextInput(sender: UDTextField){
        // 实现点击next可以切换输入框以及登陆
        switch sender.tabIndex {
        case 0:
            passwordTextField.becomeFirstResponder()
            break
        case 1:
            if requireVerify{
                verifyTextField.becomeFirstResponder()
            }else{
                login()
            }
            break
        case 2:
            login()
            break
        default:
            break
        }
    }
    
    @objc private func login(){
        if checkInput() {
            postRequest()
        }
    }
    
    private func checkInput() ->Bool{
        
        // 检查输入是否合法，不合法的不提交服务器，减少请求
        if emailTextField.text == ""{
            setErrorMsg("请输入用户名")
            emailTextField.becomeFirstResponder()
            return false
        }
        // MARK: 打开这段代码检查邮箱地址
        /*
        if emailTextField.text!.componentsSeparatedByString("@").count != 2{
            setErrorMsg("邮箱地址不正确")
            emailTextField.becomeFirstResponder()
            return false
        }
 */
        
        if passwordTextField.text == ""{
            setErrorMsg("请输入密码")
            passwordTextField.becomeFirstResponder()
            return false
        }
        
        // MARK: 打开这段代码检查密码长度
        /*
        if passwordTextField.text?.characters.count < 6{
            setErrorMsg("密码长度不足")
            passwordTextField.becomeFirstResponder()
            return false
        }
        */
        
        if requireVerify{
            if verifyTextField.text == ""{
                setErrorMsg("请输入验证码")
                verifyTextField.becomeFirstResponder()
                return false
            }
        }
        setErrorMsg("")
        return true
    }
    
    private func postingStatus(status: Bool){
        // 切换通讯状态，与服务器通讯中禁用所有按钮防止多次提交
        emailTextField.enabled = !status
        passwordTextField.enabled = !status
        verifyTextField.enabled = !status
        verifyImg.enabled = !status
        loginBtn.enabled = !status
        if status{
            spinnerBG.alpha = 1
        }else{
            spinnerBG.alpha = 0
        }
    }
    
    private func postRequest(){
        // 提交数据
        postingStatus(true)
        
        let resq = NSMutableURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.USER_LOGIN)")!)
        resq.HTTPMethod = "POST"
        resq.HTTPBody = NSString(string: "username=\(emailTextField.text!)&password=\(passwordTextField.text!)&verify=\(verifyTextField.text!)").dataUsingEncoding(NSUTF8StringEncoding)

        
        NSURLConnection.sendAsynchronousRequest(resq, queue: NSOperationQueue()) { (resp:NSURLResponse?, returnData:NSData?, err:NSError?) in
            var connected = false
            if err == nil{
                if let data = returnData{
                    print(NSString(data: data, encoding: NSUTF8StringEncoding))
                    connected = true
                    dispatch_async(dispatch_get_main_queue(), { 
                        self.handleResult(data)
                    })
                }
            }
            if !connected{
                dispatch_async(dispatch_get_main_queue(), {
                    self.setErrorMsg("网络错误")
                    self.postingStatus(false)
                })
            }
            
            
        }
    }
    
    private func handleResult(res: NSData){
        // 提交完数据后处理服务器返回的数据
        let jsonObj = try? NSJSONSerialization.JSONObjectWithData(res, options: .AllowFragments) as! NSDictionary
        if jsonObj != nil{
            if jsonObj?.objectForKey("code") != nil{
                let errCode = jsonObj?.objectForKey("code") as! Int
                if errCode != 200{
                    
                    setErrorMsg(jsonObj?.objectForKey("message") as! String)
                    requireVerify = true
                    postingStatus(false)
                    if errCode == 202 {
                        self.verifyTextField.text = ""
                        self.verifyTextField.becomeFirstResponder()
                        
                    }
                }else{
                    // MARK: 登陆成功
                    // 存储cookie NSData username
                    //let userData = jsonObj?.objectForKey("data")
                    NSUserDefaults.standardUserDefaults().setObject(emailTextField.text!, forKey: "user")
                    NSUserDefaults.standardUserDefaults().setObject(true, forKey: "orderListRefreshRequire")
                    let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies!
                    let cookiesData = NSKeyedArchiver.archivedDataWithRootObject(cookies)
                    
                    NSUserDefaults.standardUserDefaults().setObject(cookiesData, forKey: "cookies")
                    NSUserDefaults.standardUserDefaults().synchronize()
                    
                    let userData = jsonObj?.objectForKey("data") as? NSDictionary
                    if userData != nil {
                        let nickName = userData!.objectForKey("nickName") as? String
                        if nickName != nil {
                            NSUserDefaults.standardUserDefaults().setObject(nickName!, forKey: "user")
                        }
                    }
                    
//                    let appdelegate = UIApplication.sharedApplication().delegate as! AppDelegate
//                    UIApplication.sharedApplication().delegate?.window?!.rootViewController = appdelegate.mainRootVC
                    dismissViewControllerAnimated(true, completion: nil)
                }
                
                
            }
        }
        
    }

    private func setErrorMsg(message: String){
        // 显示错误信息，做一个摇头的动画
        
        msg.text = message
        if message != ""{
            if msg.alpha == 0 {
                self.msg.alpha = 1
                UIView.animateWithDuration(0.3, delay: 0, options: .CurveLinear, animations: {
                    
                    self.msg.center.y = 76
                    }, completion: { (finished) in
                        UIView.animateWithDuration(0.3, delay: 3, options: .CurveLinear, animations: {
                            self.msg.center.y = 52
                            }, completion: { (finished1) in
                                self.msg.alpha = 0
                        })
                })
            }
            
        }
    }
    
    @objc private func gotoReg(){
        // 去注册界面
        let regVC = UDRegViewController()
        regVC.delegate = self
        presentViewController(regVC, animated: true, completion: nil)
    }
    
    func dismiss(){
        // 关闭页面
        dismissViewControllerAnimated(true, completion: nil)
    }

    
    func doubleDismissRegView() {
        dismissViewControllerAnimated(true, completion: nil)
    }
        /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
